package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.MobileSuccessResult;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    //预约提交操作
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //获取到输入的验证码
        String validateCode = (String) map.get("validateCode");
        //获取到输入的手机号码
        String telephone = (String) map.get("telephone");
        //获取到Redis中的验证码信息
        Jedis resource = jedisPool.getResource();
        String redisValidateCode = resource.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        resource.close();

        //如果获取的数据不为空
        if (validateCode != null && redisValidateCode != null && validateCode.equals(redisValidateCode)) {
            //表示验证成功，需要添加预约的类型
            map.put("orderType",Order.ORDERTYPE_WEIXIN);
            //调用方法进行预约操作
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                //预约失败，直接返回一个null值
                return result;
            }
            return result;
        } else {
            //表示验证失败直接返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }


    //根据id进行查询
    @RequestMapping("/findById")
    public Result findById(int id){
        try {
            //查询成功
            MobileSuccessResult mobileSuccessResult = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,mobileSuccessResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
